<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="94px">
        <el-form-item label="项目">
          <el-select
            v-model="searchParam.projectId"
            placeholder="请选择项目"
            clearable
            filterable
            @change="projectChange"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            :disabled="!searchParam.projectId"
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            clearable
            filterable
            :disabled="!searchParam.processId"
            @change="equipChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <span v-show="!collapsed">
          <el-form-item label="产品型号">
            <el-select
              v-model="searchParam.productId"
              placeholder="请选择产品型号"
              clearable
              filterable
              @change="productChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.productCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检具类型">
            <el-select
              v-model="searchParam.gageEquipToolKind"
              placeholder="请选择量检具类型"
              clearable
              @change="toolKindChange"
            >
              <el-option
                v-for="item in useDictionary('InspectionToolKind')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检具设备">
            <el-select
              v-model="searchParam.gageEquipMarkCode"
              placeholder="请选择检具设备"
              clearable
              filterable
              :disabled="!searchParam.gageEquipToolKind"
            >
              <el-option
                v-for="item in gageEquipList"
                :key="item.toolCode"
                :label="item.toolCode"
                :value="item.toolCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="特性项">
            <el-select
              v-model="searchParam.paramId"
              placeholder="请选择特性项"
              clearable
              filterable
              :disabled="!canSelectSpecific"
              @change="search"
            >
              <el-option
                v-for="item in specificList"
                :key="item.paramCode"
                :label="item.paramName"
                :value="item.paramId"
              />
            </el-select>
          </el-form-item>
        </span>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
          <el-button type="primary" link @click="collapsed = !collapsed">
            {{ collapsed ? "展开" : "收起" }}
            <i-ep-arrowUp v-if="!collapsed" class="ml-[3px]" />
            <i-ep-arrowDown v-else class="ml-[3px]" />
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="synchronous()">
          <i-ep-plus />
          同步
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工序编码"
          prop="processCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="工序名称"
          prop="processName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="设备编码"
          prop="equipCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="设备名称"
          prop="equipName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="项目编码"
          prop="projectCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="项目名称"
          prop="projectName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="产品型号编码"
          prop="modelCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="产品型号名称"
          prop="modelName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="检具设备号编码"
          prop="gageEquipMarkCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="检具设备号名称"
          prop="gageEquipMarkName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="特性项编码"
          prop="paramCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="特性项名称"
          prop="paramName"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="参数标准"
          prop="parameterStandards"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="公差下线"
          prop="lowerLimitValue"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="公差上线"
          prop="upperLimitValue"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <pcmmeasurefeatures-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
} from "@/utils/commonData";

defineOptions({
  name: "QMSPCMPCMMEASUREFEATURES",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/dmpDosPcm/pcmmeasurefeatures/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processCode: "",
  processName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  modelId: "",
  modelCode: "",
  modelName: "",
  gageEquipId: "",
  gageEquipCode: "",
  gageEquipName: "",
  gageEquipMarkId: "",
  gageEquipMarkCode: "",
  gageEquipMarkName: "",
  paramId: "",
  paramCode: "",
  paramName: "",
};

const deleteParam = {
  api: "/dmpDosPcm/pcmmeasurefeatures/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/dmpDosPcm/pcmmeasurefeatures/get/${id}`,
    method: "get",
  })
    .then((data) => {
      data.data.isRatioUp = data.data.isRatioUp == 1;
      data.data.isRatioDow = data.data.isRatioDow == 1;
      data.data.isSingle = data.data.isSingle == 1;
      data.data.isAverage = data.data.isAverage == 1;
      data.data.isLong = data.data.isLong == 1;
      data.data.isStage = data.data.isStage == 1;
      data.data.isFeatures = data.data.isFeatures == 1;
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开测量特性定义表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改测量特性定义";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增测量特性定义";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

async function synchronous() {
  const { data } = await request({
    url: `/dmpDosPcm/pcmmeasurefeatures/synchronous`,
    method: "get",
  });
  ElMessage.success("同步成功！");
  search();
}

/** 打开测量特性定义表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "测量特性定义详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 搜索项折叠
const collapsed = ref(false);

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/dmpDosPcm/pcmmeasurefeatures/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

onMounted(() => {
  // 获取table列表
  getTableList();
  // 获取项目列表
  getProjectList();
  // 获取产品型号列表
  getProductList();
});

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id: string) {
  equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
}
function equipChange(id: string) {
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
  } else {
    searchParam.value.equipCode = "";
  }
}

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  processList.value = (await getMdmProcessProjectApi({ projectId: id })) || [];
}
function processChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
    getEquipList(id);
  } else {
    searchParam.value.processCode = "";
    equipList.value = [];
  }
}

// 获取项目列表
const projectList = ref<any>([]);
async function getProjectList() {
  projectList.value = (await getMdmprojectinfosApi({})) || [];
}
function projectChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.processId = "";
  searchParam.value.processCode = "";
  if (id) {
    const current: any =
      projectList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.projectCode = current.projectCode || "";
    getProcessList(id);
  } else {
    searchParam.value.projectCode = "";
    equipList.value = [];
    processList.value = [];
  }
}

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  productList.value = (await getMdmproductinfosApi({})) || [];
}
function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.productCode = current.productCode || "";
  } else {
    searchParam.value.productCode = "";
  }
}

// 量检具类型变化
function toolKindChange(type: string) {
  searchParam.value.gageEquipCode = "";
  searchParam.value.gageEquipMarkCode = "";
  if (type) {
    getGageEquipList(type);
  } else {
    gageEquipList.value = [];
  }
}

// 获取量检具列表
const gageEquipList = ref<any>([]);
async function getGageEquipList(type: string) {
  gageEquipList.value =
    (await getMdminspectiontoolApi({ toolKind: type })) || [];
}

// 获取特性值列表
const specificList = ref<any>([]);
async function getSpecificList() {
  specificList.value =
    (await getSpecificListApi({
      equipId: searchParam.value.equipId,
      gageEquipMarkCode: searchParam.value.gageEquipMarkCode,
      modelId: searchParam.value.productId,
      processId: searchParam.value.processId,
    })) || [];
}

// 检测必填项，筛选特性值列表
const canSelectSpecific = ref(false);
watch(
  () => searchParam.value,
  (newVal) => {
    if (
      newVal.equipCode &&
      newVal.gageEquipMarkCode &&
      newVal.productCode &&
      newVal.processCode
    ) {
      canSelectSpecific.value = true;
      getSpecificList();
    } else {
      canSelectSpecific.value = false;
    }
  },
  {
    deep: true,
  }
);
</script>
